//
//  WPUpdateDataVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/8.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPUpdateDataVC.h"
#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import "TZTestCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "LxGridViewFlowLayout.h"
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "WPHomeEditeImageVC.h"
#import "WPPhotoPreviewController.h"
#import "WPMedicalRecordsVC.h"
#import "UIImage+AsyncDraw.h"
#import "WPMineLoginVC.h"


@interface WPUpdateDataVC ()<TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UINavigationControllerDelegate>

{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    
    CGFloat _itemWH;
    CGFloat _margin;
    LxGridViewFlowLayout *_layout;
}

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *widthConstraint;
@property (nonatomic, strong) UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *snapImagesArr;
@property(nonatomic,strong)UIAlertView *alertView;

@property(nonatomic,assign)CGFloat progress;
@property(nonatomic,strong)UIImageView *firstUsingImageView;

@end

@implementation WPUpdateDataVC

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //    判断是不是第一次进这个页面
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:isFirst_Updata])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirst_Updata];
        NSString *imageName = nil;
        
        if (SCREEN_WIDTH < 375)
        {
            imageName = @"Updata_first_using5";
        }
        else if (SCREEN_WIDTH < 414)
        {
            imageName = @"Updata_first_using6";
        }
        else
        {
            imageName = @"Updata_first_using6p";
        }
        
        UIImageView *guideImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
        self.firstUsingImageView = guideImageView;
        guideImageView.userInteractionEnabled = YES;
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:guideImageView];
        
        [guideImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(keyWindow);
        }];
        
        UITapGestureRecognizer *TGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideImageViewDidClick:)];
        [guideImageView addGestureRecognizer:TGR];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"back_highlight"] forState:UIControlStateHighlighted];
    [btn sizeToFit];
    [btn addTarget:self action:@selector(backBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacer.width = -8;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    
    //图片的高度
    UIImage *image = [UIImage imageNamed:@"uploadTopImage"];
    CGFloat scale = image.size.width/image.size.height;
    self.heightConstraint.constant = (SCREEN_WIDTH-40)/scale;
    
    //    选这图片的配置
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    [self configCollectionView];
    
}

-(void)guideImageViewDidClick:(UITapGestureRecognizer *)tgr
{
    [self.firstUsingImageView removeFromSuperview];
}


//-(void)setupIntroduceLabel
//{
//    NSString *str = @"运用上载数据,可以制作成电子病历单,同时数据完成后将存入病历档案";
//    
//    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
//    paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
//    
//    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:paraStyle};
//    
//    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
//    self.introduceLabel.attributedText = attributeStr;
//}

- (void)configCollectionView {
    _layout = [[LxGridViewFlowLayout alloc] init];
    _margin = 4;
    _itemWH = (self.view.tz_width-5*10)/4;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = 8;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    _collectionView.contentInset = UIEdgeInsetsMake(-50, 10, 15, 10);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.bgView addSubview:_collectionView];
    [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.bgView);
    }];
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];
        cell.deleteBtn.hidden = YES;
    } else {
        cell.imageView.image = self.snapImagesArr[indexPath.row];
        cell.asset = _selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        
        [self pushImagePickerController];
        
    } else { // preview photos or video / 预览照片或者视频
        
        // preview photos / 预览照片
        WPPhotoPreviewController *ppc = [WPPhotoPreviewController new];
        ppc.photos = _selectedPhotos;
        ppc.currentIndex = indexPath.item;
        [self presentViewController:ppc animated:YES completion:nil];
    }
}


#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:12 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    if (sourceIndexPath.item >= _selectedPhotos.count || destinationIndexPath.item >= _selectedPhotos.count) return;
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    if (image) {
        [_selectedPhotos exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_selectedAssets exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_collectionView reloadData];
    }
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    _layout.itemCount = _selectedPhotos.count;
    
    [self.snapImagesArr removeAllObjects];
    for (UIImage *image in photos)
    {
        NSData *data = UIImageJPEGRepresentation(image, 0.3);
        UIImage *snapImage = [UIImage imageWithData:data];
        [self.snapImagesArr addObject:snapImage];
    }
    
    [_collectionView reloadData];

}


#pragma mark Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    _layout.itemCount = _selectedPhotos.count;
    
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
     [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [self.collectionView reloadData];
}

- (void)backBtnDidClick:(UIButton *)sender
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (IBAction)uploadImages:(UIButton *)btn
{
    if (!_selectedPhotos.count)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"请选择上传图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        
        return ;
    }

    btn.enabled = NO;
    self.progress = 0.0f;
    
    NSString *url = @"record/addRecord.do";
    
    NSMutableArray *pathArr = [NSMutableArray array];
    
    [_selectedPhotos enumerateObjectsUsingBlock:^(UIImage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *totalPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu.jpg",(unsigned long)idx]];
        
        NSData *data = UIImageJPEGRepresentation(obj, 0.6);
        [data writeToFile:totalPath atomically:NO];
        
        NSURL *imageURL = [NSURL fileURLWithPath:totalPath];
        
        [pathArr addObject:imageURL];
    }];
    
    [self showProgress:self.progress content:@"正在上传"];
    
//    NSDictionary *parameters = @{@"file":pathArr};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSURL *imageURL in pathArr)
        {
            [formData appendPartWithFileURL:imageURL name:@"file" error:nil];
        }

        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        self.progress = ((CGFloat)uploadProgress.completedUnitCount)/uploadProgress.totalUnitCount;

        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        if ([responseDic[@"result"] isEqualToString:@"success"])
        {
            [self showSuccessInfoWithStatus:@"上传成功"];
            
            if (self.isJump)
            {
                
                dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 500 *NSEC_PER_MSEC);
                
                dispatch_after(time, dispatch_get_main_queue(), ^{
                    //执行操作
                    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WPMedicalRecordsVC" bundle:nil];
                    WPMedicalRecordsVC *mrVC = [sb instantiateInitialViewController];
                    mrVC.isHidden = YES;
                    [self.navigationController pushViewController:mrVC animated:YES];
                    
                    mrVC.backBlock = ^
                    {
                        [self dismissViewControllerAnimated:YES completion:nil];
                    };
                });
        
            }
            else
            {
//                发出刷新的通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshNotifaction object:nil];
                
                [self backBtnDidClick:nil];
            }
        }
        else
        {
            [self dismiss];
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                self.alertView = alertView;
                
                [alertView show];
            }
            else
            {
                [self showSuccessInfoWithStatus:@"上传失败"];
            }
        }
        
        btn.enabled = YES;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
         if(error)
         {
             [self showErrorInfoWithStatus:@"网络错误"];
         }
        btn.enabled = YES;

    }];
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == self.alertView)
    {
        if (buttonIndex == 0)
        {
            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        }
    }
}


-(void)setProgress:(CGFloat)progress
{
    _progress = progress;
    if (progress < 1.0f)
    {
       [self showProgress:progress content:@"正在上传"];
    }
}

-(NSMutableArray *)snapImagesArr
{
    if (_snapImagesArr == nil)
    {
        _snapImagesArr = [NSMutableArray array];
    }
    return _snapImagesArr;
}

@end
